package ltd.nullpointer.frontend.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.boot2.core.utils.BeanUtils;
import com.boot2.core.utils.DateUtil;
import com.boot2.core.utils.HttpsClient;
import com.boot2.core.utils.ThreadPoolTaskExecutorUtil;
import lombok.extern.apachecommons.CommonsLog;
import ltd.nullpointer.frontend.dao.SensorDataDao;
import ltd.nullpointer.frontend.model.entity.SensorRainData;
import ltd.nullpointer.frontend.model.entity.SensorRainDataDetail;
import ltd.nullpointer.frontend.model.entity.up.SensorData;
import ltd.nullpointer.tcp.server.conf.ThingsNpProperties;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zhangweilin
 * @Description: xxxxx
 * @date 2019/12/15
 */
@Service
@CommonsLog
public class SensorDataService {

    @Autowired
    SensorDataDao sensorDataDao;

    @Autowired
    ThingsNpProperties thingsNpProperties;

    @Autowired
    NpAtrributeKvService npAtrributeKvService;

    ThreadPoolTaskExecutor threadPoolTaskExecutorUtil = ThreadPoolTaskExecutorUtil.createThreadPoolTaskExecutor();

    /**
     * 保存沉降数据
     *
     * @param sensordata
     */
    public void save(SensorData sensordata) {
        String sensorNo = sensordata.getSensorNo();
        boolean exists = sensorDataDao.existsBySensorNoAndMeasuringTime(sensorNo, sensordata.getMeasuringTime());
        if (exists) {
            log.warn("忽略重复检测数据，sensorNo:"+ sensordata.getSensorNo()+" ,measuringDate: "+ DateUtil.formatDate(sensordata.getMeasuringDate()));
            return;
        }
        String token = npAtrributeKvService.getTokenBySensorNo(sensordata.getSensorNo());
        String telemetryUrl = thingsNpProperties.getBaseHttpUrl() + String.format("%s/telemetry", token);
        String telemetryJson = JSONObject.toJSONString(sensordata, SerializerFeature.WriteDateUseDateFormat);
        threadPoolTaskExecutorUtil.submit(() -> {
            HttpsClient.postJson(telemetryUrl, telemetryJson);
        });
        sensorDataDao.saveAndFlush(sensordata);
    }

}
